import 'package:flutter/material.dart';
import 'package:flutter_widget/custom/custom_appbar.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter_widget/utils/platform.dart';

// ignore: must_be_immutable
class PackageInfoPage extends StatefulWidget {
  String name;
  PackageInfoPage({Key? key, required this.name}) : super(key: key);
  @override
  _PackageInfoPageState createState() => _PackageInfoPageState();
}

class _PackageInfoPageState extends State<PackageInfoPage> {
  PackageInfo _packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    version: 'Unknown',
    buildNumber: 'Unknown',
  );
  @override
  void initState() {
    if (PlatformUtils.isIOS || PlatformUtils.isAndroid) {
      getPackageInfo();
    }

    super.initState();
  }

  Future<void> getPackageInfo() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    setState(() {
      _packageInfo = info;
    });
  }

  Widget _infoTile(String title, String subtitle) {
    return ListTile(
      title: Text(title),
      subtitle: Text(subtitle.isNotEmpty ? subtitle : 'Not set'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppbar(widget.name, Theme.of(context).primaryColor),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [render(), ...renderContent()],
        ),
      ),
    );
  }

  renderContent() {
    if (PlatformUtils.isWeb) {
      return [const Text('web网页')];
    } else {
      return [
        _infoTile('App name', _packageInfo.appName),
        _infoTile('Package name', _packageInfo.packageName),
        _infoTile('App version', _packageInfo.version),
        _infoTile('Build number', _packageInfo.buildNumber)
      ];
    }
  }

  render() {
    if (PlatformUtils.isIOS) {
      return const ListTile(
        title: Text('设备平台'),
        subtitle: Text('IOS'),
      );
    }
    if (PlatformUtils.isAndroid) {
      return const ListTile(
        title: Text('设备平台'),
        subtitle: Text('Android'),
      );
    }
    if (PlatformUtils.isWeb) {
      return const Text('设备平台Web');
    }
  }
}
